package sim1011.components;

import jade.core.AID;
import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import java.io.Serializable;

import sim1011.behaviours.ComponentBehaviour;
import sim1011.starter.EctoMobileStarter;
import sim1011.starter.Logger;

public class Component extends Agent implements Serializable {
	private static final long serialVersionUID = 3846902475790740364L;
	
	public static float size(int reqCPU, int reqMEM) {
		return reqCPU * EctoMobileStarter.CPU_WEIGHT + reqMEM
				* EctoMobileStarter.MEMORY_WEIGHT;
	}
	public boolean forcedMove = false;
	private ComponentBehaviour mainB;
	private int requiredCPU;

	private int requiredMemory;

	public void afterMove() {
		Logger.log("[COMPONENT " + this.getLocalName() + "] Appena mosso");
		if (!forcedMove)
			mainB.execute();
		forcedMove = false;
		Logger.logPolicy("[COMPONENT " + this.getLocalName() + "] MOVED ON "+here().getName());
	}
	
	public long getExecutionTime() {
		return EctoMobileStarter.r.nextInt(2000) + 1;
	}

	public int getRequiredCPU() {
		return requiredCPU;
	}

	public int getRequiredMemory() {
		return requiredMemory;
	}

	private void initializeRequestResource(Object[] args) {
		this.requiredCPU = ((Integer) args[0]).intValue();
		this.requiredMemory = ((Integer) args[1]).intValue();
	}

	public void setRequiredCPU(int requiredCPU) {
		this.requiredCPU = requiredCPU;
	}

	public void setRequiredMemory(int requiredMemory) {
		this.requiredMemory = requiredMemory;
	}

	public void setup() {
		DFAgentDescription dfd = new DFAgentDescription();
		dfd.setName(getAID());
		ServiceDescription sd = new ServiceDescription();
		sd.setType("ecto-components");
		sd.setName("ecto-" + this.getLocalName());
		dfd.addServices(sd);
		try {
			DFService.register(this, dfd);
		} catch (FIPAException fe) {
			fe.printStackTrace();
		}
		Logger.log("[COMPONENT " + this.getLocalName() + "] initializing: "
				+ this.getLocalName());
		// Object[] args = this.getArguments();
		// commentata perchè le risorse richieste gliele passo dal main
		// initializeRequestResource(args);
		mainB = new ComponentBehaviour();
		addBehaviour(mainB);
	}

	public void takeDown() {
		try {
			DFService.deregister(this);
		} catch (FIPAException fe) {
			fe.printStackTrace();
		}
	}
}